﻿using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;


namespace Edu.Abstracts
{
    public class WeChatConstant
    {
        public const string LoginProvider = "WX";
    }

    public class WeChatOptions
    {
        public string Host { get; set; } = "https://api.weixin.qq.com/";

        public string AppId { get; set; }

        public string AppSecret { get; set; }
    }


    public interface IWeChatClient
    {
        Task<(string openid, string sessionKey, string unionid, int errcode, string errormsg)> code2Session(string code);
    }

    public class WeChatClient : IWeChatClient
    {
        private readonly HttpClient _client;
        private readonly WeChatOptions _options;
        public WeChatClient(HttpClient httpClient, IOptions<WeChatOptions> options)
        {
            this._client = httpClient;
            this._options = options.Value;

            this._client.BaseAddress = new System.Uri(this._options.Host);
        }

        public async Task<(string openid, string sessionKey, string unionid, int errcode, string errormsg)> code2Session(string code)
        {
            var response = await _client.GetAsync($"/sns/jscode2session?appid={_options.AppId}&secret={_options.AppSecret}&js_code={code}&grant_type=authorization_code");
            response.EnsureSuccessStatusCode();

            var result = await response.Content.ReadAsStringAsync();

            var definition = new { openid = "", session_key = "", uinionid = "", errcode = 0, errMsg = "" };

            var data = JsonConvert.DeserializeAnonymousType(result, definition);

            return (data.openid, data.session_key, data.uinionid, data.errcode, data.errMsg);

        }
    }
}
